<?php
/**
 * File: control.php
 * Author: Mihaela
 * Date: 11/1/2012
 * Modified By: CIS505 TEAM 1
 * Modified Data: 2012-11-29
 * Description: This module is the "brain" of the application and is
 *               responsible for controlling how a dynamic page is assembled.
 *
 * -Uses the services of the util.php module to connect to
 *  the MySQL database.  Note that there are connection
 *  echo statements in this module.
 *
 * -Uses the services of the view.php module to compose HTML
 *  output and echo that output.  Note that there are no
 *  echo statements in this module.
 *
 * -Uses the services of the storage.php module to talk to the
 *  MySQL server.  Note that there are no mysqli_xxxx calls
 *  in this module.
 */

/**
 * authenticate user
 */
session_start();
$userID = $_SESSION['userID'];
$userName = $_SESSION['userName'];

if (isset($_SESSION['userID'])){

require_once("header.php");
require_once("nav.php");
require_once("util.php");
require_once("view.php");
require_once("storage.php");

main();
}

else echo "<br /><br />Please<a href=index.php>Click Here</a> to log in.";

/**
 * Controls the execution of the application.
 */
function main( )
{
  $out = "";
  $errorMsg = "";

  displayHeader( );
  displayNav( );
  $errorMsg = processInternshipForm( );
  displayInternshipDataForm( ); // calls service in view.php
  $out = processInternshipListing( );
  displayErrorMessage($errorMsg); // calls service in view.php
  displayInternshipListing($out); // calls services in view.php
}

/**
 * Gets internship data from the user and inserts it in the database.
 * @return string error message produced by the call to the
 *   validateInternshipData( ) function.
 */
function processInternshipForm( )
{
  //$internshipID = 0; // to get internship ID from the form (via $_POST)
  $sponsorName = ""; // to get internship sponsorName from the form (via $_POST)
  $sponsorCity = ""; // to get internship sponsorCity from the form (via $_POST)
  $sponsorState = ""; // to get internship sponsorState (via $_POST)
  $postingDate = ""; // to get internship postingDate from the form (via $_POST)
  $internshipTitle = ""; // to get internship internshipTitle from the form (via $_POST)
  $internshipCategory = ""; // to get internship internshipCategory from the form (via $_POST)
  $isPaid = ""; // to get internship isPaid from the form (via $_POST)
 
  $errorMsg = ""; // to store error message return by validateInternshipData()

  //page served by the web server when control.php URL submitted by the browser
  debug(": Insert \$_Post", $_POST);

  if (!isset($_POST['submitBttn'])) {
    displayWelcomeMessage( );
  }

  //page served when user viewing the page selects 'submitBttn' from form
  else {
    //$internshipID = sanitize($_POST['internshipID']);
    $sponsorName = sanitize($_POST['sponsorName']);
    $sponsorCity = sanitize($_POST['sponsorCity']);
    $sponsorState = sanitize($_POST['sponsorState']);
    $postingDate = sanitize($_POST['postingDate']);
    $internshipTitle = sanitize($_POST['internshipTitle']);
    $internshipCategory = sanitize($_POST['internshipCategory']);
    $isPaid = sanitize($_POST['isPaid']);

    $errorMsg = validateInternshipData($sponsorName, $sponsorCity, $sponsorState, $postingDate, $internshipTitle, $internshipCategory, $isPaid);

    if ($errorMsg == "") { // proceed with insert into the database
      insertStudent($sponsorName, $sponsorCity, $sponsorState, $postingDate, $internshipTitle, $internshipCategory, $isPaid);
    }
  }

  return $errorMsg;
}

/**
 * Checks validity of parameters.
 * NOTE: This processing should be done in JavaScript.  A new module
 *         should be created to provide client-side services in JavaScript.
 *
 * @param string $sponsorName what the user entered for internship sponsorName
 * @param string $sponsorCity what the user entered for internship sponsorCity
 * @param string $sponsorState what the user entered for internship sponsorState
 * @param string $postingDate what the user entered for internship postingDate
 * @param string $internshipTitle what the user entered for internship internshipTitle
 * @param string $internshipCategory what the user entered for internship internshipCategory
 * @param string $isPaid what the user entered for internship isPaid
 * @return string error message if any of the parameters has invalid data.
 */
function validateInternshipData($sponsorName, $sponsorCity, $sponsorState, $postingDate, $internshipTitle, $internshipCategory, $isPaid)
{
  $errorMsg = "";

  if ($sponsorName == "" || $sponsorCity == "" || $sponsorState == "" || $internshipTitle == "" || $internshipCategory == "") {
    $errorMsg = "Don't leave empty fields";
  }
  if ((!((preg_match('/[A-Za-z]+/', $sponsorName)))) ||
     (!((preg_match('/[A-Za-z]+/', $sponsorCity)))) ||
     (!((preg_match('/[A-Za-z]+/', $sponsorState)))) ||
     //(!((preg_match('/[A-Za-z]+/', $postingDate)))) ||
     (!((preg_match('/[A-Za-z]+/', $internshipTitle)))) ||
     (!((preg_match('/[A-Za-z]+/', $internshipCategory))))) {
    $errorMsg = $errorMsg .  ".Please enter only valid names and dates";
  }
  return $errorMsg;
}

/**
 * Checks status of update button
 * Checks status of delete button
 *  if deleted is pushed it deletes record, if not, displays
 *  internship listing
 * Gets all internship records from the internship table in the database by
 *   calling selectAllInternships( ), which is in storage.php
 *
 * Creates listing by calling displayOneInternshipListing( ), which is in
 *   view.php.
 * 
 * @return string with formatted listing of all internship records.
 */
function processInternshipListing( )
{
  $out = "";
  $oneInternship = array( ); //associative array that holds internship record data
  $internships = array( ); //indexed array of internship records

  // if edit button is pressed
  if (isset($_POST['update'])) {
      $internshipID = ($_POST['internshipID']);
      $sponsorName = sanitize($_POST['sponsorName']);
      $sponsorCity = sanitize($_POST['sponsorCity']); 
      $sponsorState = sanitize($_POST['sponsorState']); 
      $postingDate = sanitize($_POST['postingDate']); 
      $internshipTitle = sanitize($_POST['internshipTitle']);
      $internshipCategory = sanitize($_POST['internshipCategory']); 
      $isPaid = sanitize($_POST['isPaid']);
    editInternship($internshipID, $sponsorName, $sponsorCity, $sponsorState, $postingDate, $internshipTitle, $internshipCategory, $isPaid);
  }
  
  //if delete button is pressed
  if (isset($_POST['delete'])) {
    $internshipID = $_POST['internshipID'];
    deleteInternship($internshipID);
  }
  //if search button is pressed
  if(isset($_POST['searchButton']))
  {
	$searchField = ($_POST['criteria']);
	$searchFor = sanitize($_POST['search']);
        $outerSort = $_POST['outerSort'];
        $innerSort = $_POST['innerSort'];
        $howMany = $_POST['howMany'];

	$internships = selectSearchedInternships($searchField, $searchFor, $outerSort, $innerSort, $howMany);
  }
  else {
	$internships = selectAllInternships();
}
  foreach ($internships as $oneInternship) {
    $out = $out . displayOneInternshipListing($oneInternship['internshipID'],
                      $oneInternship['sponsorName'], $oneInternship['sponsorCity'], 
                      $oneInternship['sponsorState'], $oneInternship['postingDate'], 
                      $oneInternship['internshipTitle'],$oneInternship['internshipCategory'],
                      $oneInternship['isPaid']);
    
  }
  debug(": Delete \$_Post", $_POST);

  return $out;
}
?>